package com.example.springboottest.controller;

import com.example.springboottest.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.List;

@Controller
public class UserController {

    private static File userDir;

    static {
        userDir = new File("users");
        if (!userDir.exists()) {
            userDir.mkdirs();
        }
    }

    @RequestMapping("/regUser")
    public void reg(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("开始处理用户注册的业务!!!");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String nickname = request.getParameter("nickname");
        String ageStr = request.getParameter("age");
        System.out.println(username + "," + password + "," + nickname + "," + ageStr);

        if (username == null || username.isEmpty() ||
                password == null || password.isEmpty() ||
                nickname == null || nickname.isEmpty() ||
                ageStr == null || ageStr.isEmpty() ||
                !ageStr.matches("[0-9]+")) {
            try {
                response.sendRedirect("/reg_info_error.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            //结束方法
            return;
        }

        int age = Integer.parseInt(ageStr);
        User user = new User(username, password, nickname, age);
        File userFile = new File(userDir, username + ".obj");
        //判断用户是否存在
        if (userFile.exists()) {
            try {
                response.sendRedirect("/have_user.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }

        try (
                FileOutputStream fos = new FileOutputStream(userFile);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
        ) {
            //序列化将对象写转化成字节
            oos.writeObject(user);

            response.sendRedirect("/reg_success.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/loginUser")
    public void login(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("开始处理用户登录业务!!!!");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username + "," + password);

        if (username == null || username.isEmpty() ||
                password == null || password.isEmpty()) {
            try {
                response.sendRedirect("/login_info_error.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }

        File userFile = new File(userDir, username + ".obj");
        if (!userFile.exists()) {
            try {
                response.sendRedirect("/login_fail.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }

        try (
                FileInputStream fis = new FileInputStream(userFile);
                ObjectInputStream ois = new ObjectInputStream(fis);
        ) {
            User user = (User) ois.readObject();
            if (user.getPassword().equals(password)) {
                response.sendRedirect("/login_success.html");
            } else {
                response.sendRedirect("/login_fail.html");
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

    @RequestMapping("/userList")
    public void userList(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("开始处理用户列表的动态页面!!!");

        File[] subs = userDir.listFiles(f -> f.getName().endsWith(".obj"));

        //遍历数组，对每一个文件进行反序列化
        //List<User> userList = new ArrayList<>();

        PrintWriter pw = null;
        try {
            response.setContentType("text/html;charset=utf-8");
            pw = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }

        pw.println("<!DOCTYPE html>");
        pw.println("<html lang=\"en\">");
        pw.println("<head>");
        pw.println("<meta charset=\"UTF-8\">");
        pw.println("<title>用户列表</title>");
        pw.println("</head>");
        pw.println("<body>");
        pw.println("<center>");
        pw.println("<h1>用户列表</h1>");
        pw.println("<table border=\"1\">");
        pw.println("<tr><td>用户名</td><td>密码</td><td>昵称</td><td>年龄</td></tr>");

        for (File sub : subs) {
            try (
                    FileInputStream fis = new FileInputStream(sub);
                    ObjectInputStream ois = new ObjectInputStream(fis);
            ) {
                User user = (User)ois.readObject();
                //userList.add(user);
                pw.println("<tr>");
                pw.println("<td>"+user.getUsername()+"</td>");
                pw.println("<td>"+user.getPassword()+"</td>");
                pw.println("<td>"+user.getNickname()+"</td>");
                pw.println("<td>"+user.getAge()+"</td>");
                pw.println("</tr>");
                System.out.println(user);
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        //System.out.println(userList);

        pw.println("</table>");
        pw.println("</center>");
        pw.println("</body>");
        pw.println("</html>");

    }

}
